from flask import Blueprint, jsonify, request
from models.entity.device_type import DeviceType
from models.entity.device import Device
import json
from utils.result import result

mod = Blueprint("core_device_type", __name__, url_prefix="/core/device_type", template_folder="templates", static_folder="static")

@mod.route('/add/',methods=['GET','POST'])
def add_device_type():
    """增加设备分类"""
    """
   {

    "name":"dd5",
    "code":"2dddd",
    "icon":"22",
    "description":"22222"
    }
    """
    if request.method == 'POST':
        tmp = {}
        data = []
        dict = json.loads(request.data.decode("utf-8"))
        device_type = DeviceType()
        try:
            device_type.from_dict(dict)
            data.append(device_type.to_dict())
        except RuntimeError as e:
            return result(success=0,error_code=-1,error_msg=e)
        if DeviceType.get_device_type_by_name(dict['name']):
            return result(success=0,error_code=-2,error_msg="名字存在")
        if DeviceType.get_device_type_by_code(dict['code']) is not None:
            return result(success=0,error_code=-2,error_msg="编码存在")
        if device_type.save():
            return result(success=1, data=data)
        else:
            return result(success=0,error_code=-2,error_msg='未知错误')



@mod.route('/edit/', methods=['GET', 'POST'])
def edit_device_type():
    """增加设备分组分类"""
    """
    {
    "id":1,
    "name":"0",
    "code":"25",
    "icon":"22",
    "description":"22222"

    }
    """
    if request.method == 'POST':
        tmp = {}
        data =[]
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        device_type = DeviceType.get_device_type_by_id(id)
        if dict['name'] != device_type.name and  DeviceType.get_device_type_by_name(dict['name']):
            return result(success=0,error_msg='名称已经存在',error_code=-1)
        if dict['code'] != device_type.code and DeviceType.get_device_type_by_code(dict['code']):
            return result(success=0,error_msg='编码已经存在',error_code=-1)
        try:
            device_type.from_dict(dict)
        except RuntimeError as e:
            return result(success=0,error_code=-1,error_msg='格式错误')
        if device_type.save():
            return result(success=1)
        else:
            return result(success=-1,error_code=-2,error_msg='未知错误')

@mod.route('/del/', methods=['GET', 'POST'])
def del_device_type():
    """增加设备分组分类"""
    """
    {
    "id":1
    }

    """
    if request.method == 'POST':
        tmp = {}
        data =[]
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        print(id)
        device_type = DeviceType.get_device_type_by_id(id)

        if len(Device.get_devices_by_type_id(id))!=0:
            return result(success=0,error_code=-3,error_msg='设备类型下存在子设备，不能删除')
        if device_type.delete():
            return result(success=1)
        else:
            return result(success=0,error_code=-2,error_msg='未知错误')


@mod.route('/get_all/', methods=['GET', 'POST'])
def get_device_type():
    """获取所有设备分类"""
    if request.method == 'GET':
        tmp = {}
        data =[]
        device_types = DeviceType.get_device_type_all()
        for item in device_types:
            data.append(item.to_dict())
        return result(data=data)

    if request.method == 'POST':
        tmp = {}
        data =[]
        device_types = DeviceType.get_device_type_all()
        for item in device_types:
            data.append(item.to_dict())
        return result(data=data)

@mod.route("/search/",methods=["POST"])
def search_device_type():
    """
    查询device_type
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    if request.method == 'POST':
        receive = request.data
        data = json.loads(receive.decode("utf-8"))
        tmp ={}
        extra =[]
        if 'query_word' in data:
            query_word = data['query_word']
        else:
            return result(success=0,error_msg='格式错误',error_code=-1)
        device_types = DeviceType.search(query_word)
        return result(data=device_types)
